package de.hfu.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

public class SimpleXMLParser {
	StringBuilder text = null;
	final int CONNECTION_TIMEOUT = 1000 * 5;
	int curPos = 0;

	public SimpleXMLParser(URL url) {
		text = new StringBuilder();
		loadUrl(url);
	}

	public SimpleXMLParser(String text) {
		this.text = new StringBuilder(text);
	}
	
	private void loadUrl(URL url) {
		try {
			// URL url = new
			// URL("http://webuser.hs-furtwangen.de/rss/hfu/hfuNews.xml");
			URLConnection urlConnection = url.openConnection();
			urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
			urlConnection.connect();			
			InputStream input = url.openStream();
			Reader reader = new InputStreamReader(input, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(reader);
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				text.append(line + "\n");
			}
			// System.out.println(text.toString());
		} catch (IOException e) {
			System.err.println("IOException while downloading url: "
					+ url.toString());
		}
	}

	private int nextStartTag(String tag, int pos) {
		return text.indexOf("<" + tag + ">", pos);
	}

	private int nextEndTag(String tag, int pos) {
		return text.indexOf("</" + tag + ">", pos);
	}

	public String nextTagContent(String tag) {
		int start = nextStartTag(tag, curPos);
		if (start == -1) {
			return "";
		}
		start += tag.length() + 2;
		curPos = start;
		int end = nextEndTag(tag, start);
		if (start >= 0 && end > start)
			return text.substring(start, end);
		return "";
	}

	public String nextTagContent() {
		int start = text.indexOf(">") + 1;
		int end = text.indexOf("<", start);
		if (start < end)
			return text.substring(start, end);
		return null;
	}
	
	public void nextTag(String tag) {
		int start = nextStartTag(tag, curPos) + tag.length() + 2;
		curPos = start;
	}
}
